package Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class FilterVisiteDao {
	private String driver = "oracle.jdbc.driver.OracleDriver";
	private String url = "jdbc:oracle:thin:@localhost:1521:xe"; // 데이터 베이스 출처
	private String user = "ara"; // 사용자 아이디
	private String password = "ara"; // 사용자 비번

	private Connection conn = null;

	public FilterVisiteDao() {
		try {
			Class.forName(driver);
			conn = getConnection();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("해당 드라이브가 존재하지 않습니다.");
		}
	}

	private Connection getConnection() {
		try {
			return DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("커넥션 생성에 실패했습니다.");
			return null;
		}
	}

	private void closeConnection() {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// /////////////////////////////////////////////////////
	public void InsertData(String v_code) {

		PreparedStatement pstmt = null;

		String sql = "insert into visite values(seq_visite.nextval,to_date(sysdate,'yy/mm/dd'),to_char(sysdate,'hh24miss'),?)";

		try {
			conn.setAutoCommit(false);
			pstmt = conn.prepareStatement(sql);

			pstmt.setString(1, v_code);

			pstmt.executeUpdate();
			conn.commit();

		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (pstmt != null) {
					pstmt.close();
				}
				closeConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void HadoopInsert(String[] data) {
//		String year,String month,String room,String count
		PreparedStatement pstmt = null;
		
		String data2[] = null;
		String sql = "insert into logdata values (seq_logdata.nextval,?,?,?,?)";

		try {
				conn.setAutoCommit(false);
				for(int i=0;i<data.length;i++){
					data2 = data[i].split("\t");
					pstmt = conn.prepareStatement(sql);
					
					pstmt.setString(1, data2[1].trim());
					pstmt.setString(2, data2[2].trim());
					pstmt.setString(3, data2[0].trim());
					pstmt.setString(4, data2[3].trim());
		
					pstmt.executeUpdate();
				}
				conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (pstmt != null) {
					pstmt.close();
				}
				closeConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
